package com.wcl.demo.ui.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.exceptions.EaseMobException;
import com.wcl.demo.R;
import com.wcl.demo.ui.adapter.GroupMsgAdapter;
import com.wcl.demo.utils.ActivityUtils;
import com.wcl.demo.utils.DialogUtils;
import com.wcl.demo.utils.ProgressUtils;
import com.wcl.demo.view.CustomDialog;
import com.wcl.demo.view.CustomToast;
import com.wcl.demo.view.SwitchButton;
import com.wcl.demo.view.viewpageanimation.CustomNewTitle;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

/**
 * Created by dllo on 15/12/2.
 */
public class GroupMsgActivity extends BaseActivity {
    private GridView group_friends;//群成员
    private GroupMsgAdapter adapter;//群消息的适配器
    private String groupid;//群id
    private List<String> members;//群成员列表
    private boolean isRefuseGroupMsg;//是否屏蔽群组消息
    private SharedPreferences sp;//定义缓存文件,用于存储是否屏蔽群消息
    private SharedPreferences.Editor editor;//定义缓存编辑对象
    /***
     * 初始化
     */
    @Bind(R.id.refuseGroupMsgSb)
    SwitchButton refuseGroupMsgSb;

    @Bind(R.id.groupmsg_id)
    TextView groupmsg_id;

    @Bind(R.id.groupmsg_member_hide)
    LinearLayout groupmsg_member_hide;

    @Bind(R.id.groupmsg_member_diss)
    Button groupmsg_member_diss;

    @Bind(R.id.groupmsg_diss)
    Button groupmsg_diss;

    /***
     * 点击事件
     *
     * @param v
     */
    @OnClick(R.id.groupmsg_remove)
    void groupmsg_remove(View v) {
        DialogUtils.deleteChat(this, groupid);
//        //清空和某个user的聊天记录(包括本地)，不删除conversation这个会话对象
//        EMChatManager.getInstance().clearConversation(groupid);
    }

    @OnClick(R.id.groupmsg_blacklist)
    void groupmsg_blacklist(View v) {
        Bundle bundle = new Bundle();
        bundle.putString("groupid", groupid);
        ActivityUtils.startToActivity(this, BlackListActivity.class, bundle);
    }

    ;


    @OnClick(R.id.groupmsg_back)
    void groupmsg_back(View v) {
        finish();
    }

    @OnClick(R.id.groupmsg_diss)
    void groupmsg_diss(View v) {
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setMessage("确认后,此群将被解散");
        builder.setTitle("提示信息");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                try {
                    EMGroupManager.getInstance().exitAndDeleteGroup(groupid);//需异步处理
                } catch (EaseMobException e) {
                    e.printStackTrace();
                }
                Bundle bundle = new Bundle();
                bundle.putInt("tab", 0);
                ActivityUtils.startToActivity(GroupMsgActivity.this, MainActivity.class, bundle);
                CustomToast.toastShow(GroupMsgActivity.this, "该群已被解散");
                finish();

            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    //开关状态监听
    @OnCheckedChanged(R.id.refuseGroupMsgSb)
    public void setRefuseGroupMsgSb(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            editor.putBoolean("RGM_ISCHECKED", true).commit();
            try {
                Log.i("lanouqq", isChecked + "<--//");
                EMGroupManager.getInstance().blockGroupMessage(groupid);//需异步处理
            } catch (EaseMobException e) {
                e.printStackTrace();
            }
        } else {
            editor.putBoolean("RGM_ISCHECKED", false).commit();

            try {
                Log.i("lanouqq", isChecked + "<==//");
                EMGroupManager.getInstance().unblockGroupMessage(groupid);//需异步处理
            } catch (EaseMobException e) {
                e.printStackTrace();
            }
        }
    }

    private EditText editText;
    private String newTitle;
    private CustomNewTitle newTitleDialog;
    private String owner;

    @OnClick(R.id.groupmsg_changename)
    void groupmsg_changename(View v) {

        newTitleDialog = new CustomNewTitle(GroupMsgActivity.this);
        editText = (EditText) newTitleDialog.getEditText();

        Log.i("lanou78", editText.getText().toString().trim() + "<--->");
        newTitleDialog.setOnPositiveListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                newTitleDialog.dismiss();
                newTitle = editText.getText().toString().trim();
                //groupId 需要改变名称的群组的id
                //changedGroupName 改变后的群组名称
                try {
                    EMGroupManager.getInstance().changeGroupName(groupid, editText.getText().toString().trim());//需异步处理
                } catch (EaseMobException e) {
                    Log.i("lanou1", "抛出异常");
                    e.printStackTrace();
                }
            }
        });
        newTitleDialog.setOnNegativeListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                newTitleDialog.dismiss();
            }
        });
        newTitleDialog.show();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_groupchatmsg;
    }


    @Override
    protected void initView() {
        final Bundle bundle = ActivityUtils.fromSrc(this);
        if (bundle != null) {
            this.groupid = bundle.getString("groupid");
            Log.i("lanou1", "------------->" + groupid);
        }
        sp = this.getSharedPreferences("button_state", Context.MODE_WORLD_READABLE);
        editor = sp.edit();
        if (sp.getBoolean("RGM_ISCHECKED", true)) {
            refuseGroupMsgSb.setChecked(sp.getBoolean("RGM_ISCHECKED", false));
            Log.i("lanouqq", refuseGroupMsgSb.isChecked() + "");
        }

        group_friends = (GridView) findViewById(R.id.group_friends);
        adapter = new GroupMsgAdapter();
        group_friends.setAdapter(adapter);
        groupmsg_id.setText(groupid);

        group_friends.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                if (position > members.size() - 1) {
                    Bundle bundle1 = new Bundle();
                    bundle1.putString("groupid", groupid);
                    bundle1.putString("owner", owner);
                    if (position == members.size()) {
                        bundle1.putString("add", "add");
                    } else {
                        bundle1.putString("add", "remove");
                    }
                    ActivityUtils.startToActivity(GroupMsgActivity.this, GroupAddFriendActivity.class, bundle1);
                } else {
                    CustomDialog.Builder builder = new CustomDialog.Builder(parent.getContext());
                    builder.setMessage("确认将此成员加入至此群黑名单");
                    builder.setTitle("提示");
                    builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();

                            try {
                                EMGroupManager.getInstance().blockUser(groupid, members.get(position));//需异步处理
                            } catch (EaseMobException e) {
                                e.printStackTrace();
                            }
                            refresh();

                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();
                }

                return false;
            }
        });

    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            EMGroupManager.getInstance().createOrUpdateLocalGroup(group);
            Log.i("lanou1", group.getMembers().toString() + "<<--->>" + group.getMembers().size());
            members = group.getMembers();
            owner = group.getOwner();
            if (owner.equals(EMChatManager.getInstance().getCurrentUser())) {
                groupmsg_member_hide.setVisibility(View.VISIBLE);
                groupmsg_member_diss.setVisibility(View.GONE);
                groupmsg_diss.setVisibility(View.VISIBLE);

            } else {
                groupmsg_member_hide.setVisibility(View.GONE);
                groupmsg_member_diss.setVisibility(View.VISIBLE);
                groupmsg_diss.setVisibility(View.GONE);

            }
            adapter.addData(members, groupid, owner);
            Log.i("lanou333", "aaaaa");
            adapter.notifyDataSetChanged();
            return false;
        }
    });
    EMGroup group;

    @Override
    protected void initData() {

        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    //   List<EMGroup> grouplist = EMGroupManager.getInstance().getGroupsFromServer();//需异步处理
                    group = EMGroupManager.getInstance().getGroupFromServer(groupid);
                    handler.sendEmptyMessage(200);

                } catch (EaseMobException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        ProgressUtils.dismissProgress();
    }

    private void refresh() {
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        refresh();
    }


}
